<template>
  <a-modal
    class="image-out-painting"
    v-model:open="visible"
    title="AI 扩图"
    :footer="null"
    @cancel="closeModal"
    width="80vw"
  >
    <a-row :gutter="[24, 24]">
      <!-- 图像要求 -->
      <a-col span="24" style="margin-bottom: 16px">
        <a-card title="图像要求" size="small">
          <a-descriptions layout="vertical" bordered size="small">
            <a-descriptions-item label="格式">JPG、JPEG、PNG、HEIF、WEBP</a-descriptions-item>
            <a-descriptions-item label="大小">不超过10MB</a-descriptions-item>
            <a-descriptions-item label="分辨率"
              >不低于512×512像素且不超过4096×4096像素</a-descriptions-item
            >
            <a-descriptions-item label="单边长度范围">[512,4096]（单位：像素）</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>

      <!-- 原始图片 -->
      <a-col span="12">
        <h4>原始图片</h4>
        <img
          :src="picture?.host + picture?.originalUrl"
          :alt="picture?.name"
          style="max-width: 100%; height: auto; margin-bottom: 8px"
        />
      </a-col>

      <!-- 扩图结果 -->
      <a-col span="12">
        <h4>扩图结果</h4>
        <a-spin
          v-if="!resultImageUrl && taskId"
          tip="扩图中..."
          style="min-height: 200px; display: flex; align-items: center; justify-content: center"
        >
          <div class="spin-content"></div>
        </a-spin>
        <img
          v-else-if="resultImageUrl"
          :src="resultImageUrl"
          :alt="picture?.name"
          style="max-width: 100%; height: auto"
        />
      </a-col>
    </a-row>

    <!-- 操作按钮 -->
    <a-space
      direction="horizontal"
      style="display: flex; justify-content: center; margin-top: 16px"
    >
      <a-button type="primary" :loading="!!taskId" ghost @click="createTask">生成图片</a-button>
      <a-button type="primary" v-if="resultImageUrl" :loading="uploadLoading" @click="handleUpload"
        >应用结果</a-button
      >
    </a-space>
  </a-modal>
</template>

<script setup lang="ts">
import { onUnmounted, ref } from 'vue'
import {
  createPictureOutPaintingTaskUsingPost,
  getPictureOutPaintingTaskUsingGet,
  uploadPictureByUrlUsingPost,
  uploadPictureUsingPost,
} from '@/api/pictureController'
import { message } from 'ant-design-vue'

interface Props {
  picture?: API.PictureVO
  spaceId: string
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>()
const resultImageUrl = ref<string>()

// 任务 id
let taskId = ref<string>()

/**
 * 创建任务
 */
const createTask = async () => {
  if (!props.picture?.id) {
    return
  }
  const res = await createPictureOutPaintingTaskUsingPost({
    pictureId: props.picture.id,
    // 可以根据需要设置扩图参数
    parameters: {
      xScale: 2,
      yScale: 2,
    },
  })
  if (res.code === 0 && res.data) {
    message.success('创建任务成功，请耐心等待，不要退出界面')
    console.log(res.data.output.taskId)
    taskId.value = res.data.output.taskId
    // 开启轮询
    startPolling()
  } else {
    message.error('创建任务失败，' + res.message)
  }
}

// 轮询定时器
let pollingTimer: NodeJS.Timeout = null

// 清理轮询定时器
const clearPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value = null
  }
}

// 开始轮询
const startPolling = () => {
  if (!taskId.value) return

  pollingTimer = setInterval(async () => {
    try {
      const res = await getPictureOutPaintingTaskUsingGet({
        taskId: taskId.value,
      })
      if (res.code === 0 && res.data) {
        const taskResult = res.data.output
        if (taskResult.taskStatus === 'SUCCEEDED') {
          message.success('扩图任务成功')
          resultImageUrl.value = taskResult.outputImageUrl
          clearPolling()
        } else if (taskResult.taskStatus === 'FAILED') {
          message.error('扩图任务失败' + res.data.message)
          clearPolling()
        }
      }
    } catch (error) {
      console.error('轮询任务状态失败', error)
      message.error('检测任务状态失败，请稍后重试')
      clearPolling()
    }
  }, 3000) // 每隔 3 秒轮询一次
}

// 清理定时器，避免内存泄漏
onUnmounted(() => {
  clearPolling()
})

const uploadLoading = ref<boolean>(false)

const handleUpload = async () => {
  uploadLoading.value = true
  try {
    const params: API.PictureUploadRequest = {
      fileUrl: resultImageUrl.value,
      spaceId: props.spaceId,
    }
    if (props.picture) {
      params.id = props.picture.id
    }
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.code === 0 && res.data) {
      message.success('图片上传成功')
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data)
      // 关闭弹窗
      closeModal()
    } else {
      message.error('图片上传失败，' + res.message)
    }
  } catch (error) {
    message.error('图片上传失败')
  } finally {
    uploadLoading.value = false
  }
}

// 是否可见
const visible = ref(false)

// 打开弹窗
const openModal = () => {
  visible.value = true
}

// 关闭弹窗
const closeModal = () => {
  visible.value = false
}

// 暴露函数给父组件
defineExpose({
  openModal,
})
</script>

<style scoped>
.image-out-painting {
  //text-align: center;
  text-align: left;
}

.spin-content {
  border-radius: 4px;
  background-color: #f0f2f5;
}
</style>
